package com.c78.fz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.c78.fz.mapper.HistoryMapper;
import com.c78.fz.model.entity.History;
import com.c78.fz.service.ClientService;
import com.c78.fz.common.result.Result;
import com.c78.fz.mapper.ClientMapper;
import com.c78.fz.model.entity.Client;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class ClientServiceImpl implements ClientService {
    @Resource
    ClientMapper clientMapper;

    @Resource
    HistoryMapper historyMapper;

    @Override
    public Result getClientPage(String name, String phone, Integer pageNum, Integer pageSize) {
        Page<Client> page = Page.of(pageNum,pageSize);
        clientMapper.selectPage(page,name,phone);
        return Result.ok(page);
    }

    @Override
    public Result saveClient(Client client) {
        if(clientMapper.insert(client)>0){
            return Result.ok("添加客户信息成功");
        }
        return Result.error("添加客户信息失败");
    }

    @Override
    public Result getClientById(Integer id) {
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Client::getId,id);
        Client client = clientMapper.selectOne(queryWrapper);
        return Result.ok(client);
    }

    @Override
    public Result updateClient(Client client) {
        if(clientMapper.updateById(client)>0){
            return Result.ok("修改客户信息成功");
        }
        return Result.error("修改客户信息失败");
    }

    @Override
    public Result deleteClient(Integer id) {
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Client::getId,id);
        if(clientMapper.delete(queryWrapper)>0){
            LambdaQueryWrapper<History> query = new LambdaQueryWrapper<>();
            query.eq(History::getClientId,id);
            historyMapper.delete(query);
            return Result.ok("删除客户信息成功");
        }
        return Result.error("删除客户信息失败");
    }

    @Override
    public Result getClient() {
        return Result.ok(clientMapper.selectList(null));
    }
}
